import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../components/DialogYesNo.dart';
import '../components/DialogYesNoColor.dart';
import '../resources.dart';

class Toast {
  static showToast(BuildContext context, String msg, {bool isShort = true}) {
    if (msg.isNotEmpty) {
      ToastOverlay.toast(context, msg, showTime: isShort ? 3000 : 5000);
    }
  }

  static dialog(Widget widget, {bool barrierDismissible = false}) {
    showDialog(
        context: appContext,
        builder: (context) {
          return widget;
        },
        barrierDismissible: barrierDismissible);
  }

  static showLoading({String msg = '', bool dismissible = false}) {
    if (msg.isEmpty) {
      msg = word.loading;
    }
    dialog(_IconWidget('', msg, dismissible: dismissible),
        barrierDismissible: dismissible);
  }

  static showIconToast(String msg, {String asset = ''}) {
    dialog(_IconWidget(asset, msg));
  }

  static void close() {
    Nav.pop(result: backResult(NORMAL_CODE, ''));
  }

  static showDialogWidget({required Widget child, bool dismissible = true}) {
    dialog(
        WillPopScope(
          onWillPop: () {
            ///当dismissible是false，这里会拦截，dialog就不会关闭
            return Future.value(dismissible);
          },
          child: Material(
            //创建透明层
            type: MaterialType.transparency,
            child: SizedBox(
                height: double.infinity,
                width: double.infinity,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [child],
                )),
          ),
        ),
        barrierDismissible: dismissible);
  }

  static showYesNo(
      {String title = "",
      String content = "",
      String cancelText = "",
      String confirmText = "",
      Function()? cancelFunc,
      Function()? confirmFunc,
      bool showCancel = true,
      bool dismissible = true}) {
    DialogYesNo.show(
      title: title,
      content: content,
      cancelText: cancelText,
      confirmText: confirmText,
      cancelFunc: cancelFunc,
      confirmFunc: confirmFunc,
      showCancel: showCancel,
      dismissible: dismissible,
    );
    return;
  }

  static showYesNoColor(
      {String title = "",
      String content = "",
      String cancelText = "",
      String confirmText = "",
      Function()? cancelFunc,
      Function()? confirmFunc,
      bool showCancel = true,
      bool dismissible = true}) {
    DialogYesNoColor.show(
      title: title,
      content: content,
      cancelText: cancelText,
      confirmText: confirmText,
      cancelFunc: cancelFunc,
      confirmFunc: confirmFunc,
      showCancel: showCancel,
      dismissible: dismissible,
    );
    return;
  }
}

class _IconWidget extends StatelessWidget {
  final String asset;
  final String msg;
  bool dismissible;

  _IconWidget(this.asset, this.msg, {this.dismissible = true});

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        ///当dismissible是false，这里会拦截，loading就不会关闭
        return Future.value(dismissible);
      },
      child: MediaQuery(
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
        child: Material(
          //创建透明层
          type: MaterialType.transparency, //透明类型
          child: SizedBox(
            height: double.infinity,
            width: double.infinity,
            child: Center(
              child: Container(
                height: 100,
                constraints: const BoxConstraints(minWidth: 100),
                decoration: const BoxDecoration(
                  color: Color(0xff323232),
                  borderRadius: BorderRadius.all(Radius.circular(3.0)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    asset.isEmpty
                        ? const CupertinoActivityIndicator(
                            color: ColorUtils.color_FFFFFF,
                            radius: 15,
                          )
                        : assetImage(asset,
                            width: 40.0, height: 40.0, fit: BoxFit.fill),
                    msg.isEmpty
                        ? const SizedBox()
                        : Container(
                            margin: const EdgeInsets.only(
                                top: 12, left: 12, right: 12),
                            child: Text(
                              msg,
                              style: const TextStyle(
                                color: ColorUtils.color_FFFFFF,
                                fontSize: 14.0,
                              ),
                            ),
                          ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class ToastOverlay {
  static OverlayEntry? _overlayEntry;
  static String? _msg;
  static DateTime? _startedTime;

  static void toast(BuildContext context, String msg,
      {int showTime = 1000,
      Color bgColor = const Color(0xBB000000),
      Color textColor = Colors.white,
      bool positionTop = false}) async {
    _msg = msg;
    _startedTime = DateTime.now();
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(builder: (BuildContext context) {
        return Positioned(
          //top值，可以改变这个值来改变toast在屏幕中的位置
          top: positionTop
              ? MediaQuery.of(context).size.height * (0.25)
              : (MediaQuery.of(context).size.height * (0.75) -
                  MediaQuery.of(context).viewInsets.bottom),
          child: Container(
            alignment: Alignment.center,
            width: MediaQuery.of(context).size.width,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0),
              child: Center(
                child: Card(
                  color: bgColor,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10, vertical: 10),
                    child: Text(
                      _msg!,
                      style: TextStyle(fontSize: 14, color: textColor),
                      textAlign: TextAlign.center,
                      maxLines: 8,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      });
      //插入到整个布局的最上层
      Overlay.of(context).insert(_overlayEntry!);
    } else {
      //重新绘制UI，类似setState
      _overlayEntry?.markNeedsBuild();
    }
    // 等待时间
    await Future.delayed(Duration(milliseconds: showTime));
    int closeTime = DateTime.now().difference(_startedTime!).inMilliseconds;
    if (closeTime > showTime) {
      _overlayEntry?.markNeedsBuild();
      await Future.delayed(Duration(milliseconds: closeTime - showTime));
    }
    try {
      if (_overlayEntry != null) {
        _overlayEntry?.remove();
        _overlayEntry = null;
      }
    } on Exception catch (e) {}
  }
}
